package com.tanhua.server.interceptor;


import com.alibaba.fastjson.JSON;
import com.tanhua.domain.db.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.http.HttpStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class TockenIntercepter implements HandlerInterceptor {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object handler){
        log.info("请求的路径"+request.getRequestURL());

        //获取token
        String token = request.getHeader("Authorization");
        log.info(token);
        if (StringUtils.isNotEmpty(token)){
          User user= getUserByToken(token);
          log.info("登录用户：{}",user);
          //如果有用户信息
          if (null !=user){
              UserHolder.setUser(user);
              return true;
          }
        }
        response.setStatus(HttpStatus.SC_UNAUTHORIZED);
        return false;
    }

    public User getUserByToken(String token) {
        String user = stringRedisTemplate.opsForValue().get(token);
        //没有用户信息说明token已经超过了有效期
        if (null==user){
            return null;
        }
        //延长有效期
        stringRedisTemplate.expire(token,7,TimeUnit.DAYS);
        User loginUser = JSON.parseObject(user, User.class);
        return loginUser;
    }

}
